package domain.service;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

import com.google.appengine.api.datastore.Text;

import domain.data.QnAPersistenceManager;
import domain.model.Emails;
import domain.model.Server;
import domain.string.Replace;



public class Whois {
	public Whois(String domain)
	{
		domain = domain.toLowerCase();
        try {
        	PersistenceManager psm = QnAPersistenceManager.get().getPersistenceManager();
        	
            URL url = new URL("http://o2tv.vn/whois.php?domain="+domain);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setReadTimeout(500000);
			connection.setConnectTimeout(1000000);
			BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), Charset.forName("iso-8859-1")));
			String content = "";
			while(1==1)
			{
				String str = reader.readLine();
				if(str==null) break;
				content+=str;	
			}
            Document doc = Jsoup.parse(content); 
         
            String str  = doc.select("body").html();
            
            Pattern p = Pattern.compile("[^ :]+@[^ ]+");

	        Matcher m = p.matcher(str.replaceAll("\\<.*?\\>", " "));

	        Query query = psm.newQuery(domain.model.Whois.class);
	        query.setFilter("name=='"+domain+"'");
	        @SuppressWarnings("unchecked")
			List<domain.model.Whois> check = (List<domain.model.Whois>) query.execute();
	        if(check.size() <= 0)
	        {
	        	domain.model.Whois whois = new domain.model.Whois();
	        	whois.setName(domain);
	        	Text text = new Text(str);
	        	whois.setWhois(text);
	        	whois.setLastUpdateDate(new Date());
		        while (m.find()) {
		        	if(!whois.getEmail().contains(m.group().toLowerCase().trim().replaceAll("\\(", "").replaceAll("\\)", "")))
		        	{
		        		whois.addEmail(m.group().toLowerCase().trim().replaceAll("\\(", "").replaceAll("\\)", ""));
		        		PersistenceManager psm1 = QnAPersistenceManager.get().getPersistenceManager();
		        		Emails email = new Emails();
		        		email.setDomain(domain);
		        		email.setEmail(m.group().toLowerCase().trim().replaceAll("\\(", "").replaceAll("\\)", ""));
		        		psm1.makePersistent(email);
		        	}
		        }
		        //
		        p = Pattern.compile("(([\\W]*Name Server[\\W]*|nserver:[\\W]*|Nameservers:[\\W]*|Servers:[\\W]+)[\\w-]+[.]+[\\w-_]+[.]+[\\w-_]+[.]*[\\w-_]*+[.]*[\\w-_]*|[\\w-]+[.]+[\\w-_]+[.]+[\\w-_]+[.]+[\\w-_]+[.]+[\\w-_]+)", Pattern.CASE_INSENSITIVE);

		        m = p.matcher(str.replaceAll("\\<.*?\\>", " "));

		        String save = null;
		        
		        while (m.find()) {
		        	save = Pattern.compile("([\\W]*Name Server[\\W]*|nserver:[\\W]*|Nameservers:[\\W]*|Servers:[\\W]+)",Pattern.CASE_INSENSITIVE).matcher(m.group()).replaceAll("").trim().toLowerCase();
		        	if(!whois.getServer().contains(save))
		        	{
		        		whois.addServer(save);
		        		PersistenceManager psm1 = QnAPersistenceManager.get().getPersistenceManager();
		        		Server server = new Server();
		        		server.setName(save);
		        		server.setDomain(domain);
		        		psm1.makePersistent(server);
		        	}
		        }
		        
		        //
		        p = Pattern.compile("(Creation Date:|Created On:|created:|\\[Created on\\]|Domain Create Date:|registered:|Registration Date:|Entry created:[\\W]+)[ ]*[\\w- \\/:.]+",Pattern.CASE_INSENSITIVE);

		        m = p.matcher(str.replaceAll("\\<.*?\\>", " "));

		        while (m.find()) {
		        	whois.setCreatedDate(m.group().replaceAll("(Creation Date:|Created On:|created:|\\[Created on\\]|Created:|Domain Create Date:|registered:|Registration Date:|Created on:|Entry created:[\\W]+)", "").trim().replaceAll("\\/", "-"));
		        }
		        
		        //
		        p = Pattern.compile("(Expiration Date:|expires:|\\[Expires on\\]|Expire Date:|expire:|paid-till:|last-update:|Renewal date:[\\W]+)[ ]*[\\w- \\/:.]+",Pattern.CASE_INSENSITIVE);

		        m = p.matcher(str.replaceAll("\\<.*?\\>", " "));

		        while (m.find()) {
		        	whois.setExpirationDate(m.group().replaceAll("(Expiration Date:|expires:|\\[Expires on\\]|Expire Date:|expire:|paid-till:|last-update:|Renewal date:[\\W]+)", "").trim().replaceAll("\\/", "-"));	
		        }
		        
		        //
		        p = Pattern.compile("(ADMINISTRATIVE CONTACT INFO[\\W]+|Registrant:[\\W]*|Registrant Name:[ ]*|Administrative Contact :[\\W]+|person:[\\W]*|\\[Registrant\\][\\W]*|Registrant[\\W]*Name:|registrar:|Domain Owner:[\\W]+)[a-z0-9 ,.\\-\\_]+", Pattern.CASE_INSENSITIVE);

		        m = p.matcher(str.replaceAll("\\<.*?\\>", " "));

		        while (m.find()) {
		        	save = Pattern.compile("(ADMINISTRATIVE CONTACT INFO[\\W]+|Registrant:[\\W]*|Registrant Name:[ ]*|Administrative Contact :[\\W]+|person:[\\W]*|\\[Registrant\\][\\W]*|Registrant[\\W]*Name:|registrar:|Domain Owner:[\\W]+)",Pattern.CASE_INSENSITIVE).matcher(m.group()).replaceAll("").trim();
		        	whois.setUser(save);
		        	whois.setAliasUser(Replace.replace(save));
		        }
		        
		        psm.makePersistent(whois);
	        } 

        } catch (MalformedURLException e) {
            // ...
        } catch (IOException e) {
            // ...
        }

	}
//	public static void main( String args[])
//	{
//		new Whois("ketoan.org");
//	}
}
